package com.yonyou.gmmc.service.points.eventhandle;

import org.marketing.common.dto.EventDataDTO;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.EventShoppingJDDTO;
import org.marketing.common.event.enums.EventConstant;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.event.enums.EventConstant.EventBizType;
import org.marketing.common.util.MapConverUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yonyou.gmmc.service.points.exception.PointsException;
import com.yonyou.gmmc.service.points.service.PointsPayService;
import com.yonyou.gmmc.service.points.util.SpringUtil;

/**
 * 京东下单结果事件
 * 
 * @author BENJAMIN
 *
 */
public class ShoppingJDEventHandler extends AbstractEventHandle {

	private static Logger logger = LoggerFactory.getLogger(ShoppingJDEventHandler.class);

	// 商城订单
	private static EventBizType BizType = EventConstant.EventBizType.SHOPPIING_ORDER;
	// 用户下单
	private static EventBizStep BizStep = EventConstant.EventBizStep.SHOPPIING_ORDER_POINTS;

	@Override
	protected String getHandleInfo() {
		return "京东下单失败，补偿用户积分";
	}

	
	/**
	 * 主要进行数据转换
	 */
	@Override
	protected EventShoppingJDDTO preTransform(BizEvent event) {
		EventShoppingJDDTO o = new EventShoppingJDDTO();
		try {
			o = (EventShoppingJDDTO) MapConverUtil.map2POStrict(event.getEventData(), o);
			logger.info(o.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			this.backInfo = "eventData中的业务数据不能识别：" + e.getMessage();
			throw new PointsException(PointsException.EVENT_CONVERT_FAILD,"eventData中的业务数据不能识别");
		}
		return o;
	}

	/**
	 * 积分处理的逻辑
	 */
	@Override
	protected boolean pay(EventDataDTO eventData) throws PointsException{
		//获取到业务数据
		EventShoppingJDDTO thisEventData = (EventShoppingJDDTO)eventData;
		boolean isOrdered  =thisEventData.isOrdered();
		if(isOrdered){
			//1.下单成功的事件，暂时没有逻辑
			logger.info("京东下单成功，暂无后续操作");
		}else{
			//2.下单失败的时间，需要将用户的积分还回去
			logger.info("京东下单失败，进行积分回滚");
			PointsPayService pointsPayService = (PointsPayService)SpringUtil.getBean("pointsPayService");;
			Long points = thisEventData.getPointNums(); 
			//1.处理积分的事情
			try {
				//执行积分变动
				pointsPayService.payPointsToUser(points, thisEventData.getUserId(),"",this.getHandleInfo(),thisEventData.getShoppingOrderNo(),BizStep.getCode(),thisEventData.getShoppingOrderNo());
			} catch (Exception e) {
				logger.error("积分补偿失败========要重点关注",e);
				this.backInfo="积分补偿失败========要重点关注";
				throw new PointsException(90002,"积分补偿失败");
			}
		}
		return true;
	}


}
